import _ from 'lodash'
import { CommonStringObjectType } from '@/framework/types/common-data'

export const deepCloneWithNull = (dest: any, src: any) => {
  const srcMap = new Map(Object.entries(src))
  const destMap = new Map(Object.entries(dest))
  srcMap.forEach((value, key) => {
    if (destMap.has(key)) {
      if (value) {
        dest[key] = _.cloneDeep(value)
      }
    }
  })
}

export const isEmpty = (data: any) => {
  if (data === undefined || data == null) {
    return true
  } else if (data instanceof Array) {
    return data.length === 0
  } else if (data instanceof Map) {
    return data.size === 0
  } else if (typeof data === 'string') {
    return data.length === 0 || data === ''
  } else if (typeof data === 'object') {
    return Object.keys(data).length === 0
  } else {
    return false
  }
}

export const isNotEmpty = (data: any) => !isEmpty(data)

export const strLF2HtmlLF = (str: string) => {
  if (isNotEmpty(str)) {
    str = str.replace(/\n|\\n/g, '<br/>')
  }
  return str
}

export const strRemoveLF = (str: string) => {
  if (isNotEmpty(str)) {
    str = str.replace(/\n|\\n/g, '')
  }
  return str
}

export const doFunctions = (...functions: Array<(...arg: any) => any>) => {
  functions.forEach((func) => {
    func()
  })
}
export const log = (...a: Array<any>) => {
  const array = new Error().stack?.split(' at ')
  let fileName = array && array[2]
  if (fileName?.startsWith('app.config.globalProperties')) {
    fileName = array && array[3].split('?')[0].split('/').pop()
  } else {
    fileName = array && array[2].split('?')[0].split('/').pop()
  }
  console.log('[' + fileName + ']', ...a)
  return true
}

export const getScreenHeight = () => {
  if (window.innerHeight) {
    // 现代浏览器
    return window.innerHeight
  } else if (document.documentElement && document.documentElement.clientHeight) {
    // 老版本IE浏览器
    return document.documentElement.clientHeight
  } else if (document.body) {
    // 老版本其他浏览器
    return document.body.clientHeight
  }
  throw new Error('获取屏幕高度异常')
}

export const getScreenWidth = () => {
  if (window.innerWidth) {
    // 现代浏览器
    return window.innerWidth
  } else if (document.documentElement && document.documentElement.clientWidth) {
    // 老版本IE浏览器
    return document.documentElement.clientWidth
  } else if (document.body) {
    // 老版本其他浏览器
    return document.body.clientWidth
  }
  throw new Error('获取屏幕宽度异常')
}

export const dispatchMouseEvent = (DOM_ID: string, eventName = 'click') => {
  const event = new MouseEvent(eventName, {
    view: window,
    bubbles: true,
    cancelable: true
  })
  const DOM = document.getElementById(DOM_ID)
  if (DOM) DOM.dispatchEvent(event)
  else throw new Error('根据DOM的id无法找到对应DOM，请检查')
}

export const getDate = (date = new Date(), split = '-') => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  return year + split + month + split + day
}

export const getStartAndEndOfWeek = (date = new Date(), split = '-') => {
  const dayOfWeek = date.getDay()
  const numDaysToSunday = dayOfWeek === 0 ? 7 : dayOfWeek - 1
  const numDaysToSaturday = dayOfWeek === 0 ? 6 : 7 - dayOfWeek

  const firstDay = new Date(date)
  firstDay.setDate(date.getDate() - numDaysToSunday)

  const lastDay = new Date(date)
  lastDay.setDate(date.getDate() + numDaysToSaturday)

  return {
    firstDay: getDate(firstDay, split),
    lastDay: getDate(lastDay, split)
  }
}

export const getArrayTopN = (array: Array<any>, top?: number) => {
  if (top === undefined || top < 0) return array
  else return array.slice(0, Math.min(array.length, top))
}

export const getAssetsFile = (url: string) => new URL(`../../assets/images/${url}`, import.meta.url).href

export const getFrameworkAssetsFile = (url: string) => new URL(`../assets/images/${url}`, import.meta.url).href

export const clearObjectAllValue = (object: CommonStringObjectType) => {
  Object.keys(object).forEach((key) => {
    object[key] = ''
  })
}

export const showDefaultString = (string: string | number | null | undefined, default_string = '-') =>
  String(string === 0 ? string : string || default_string)

export const addPropertyValueToObject = (object: { [key: string]: Array<any> }, property: string, value: any) => {
  if (Object.prototype.hasOwnProperty.call(object, property)) object[property].push(value)
  else object[property] = [value]
}

export const updateTabLineWidth = (tabLineWidth: Ref<string>, parentId: string) => {
  const activeTab = document.querySelector(`#${parentId} .van-tab--active`)
  if (activeTab) {
    const width = activeTab.clientWidth as number
    tabLineWidth.value = `${width - 25}px`
  }
}

export const parseCssValue = (value: string | number = 'auto', unit = 'px') => {
  return value === 'auto' ? value : isNaN(Number(value)) ? value : Number(value) + unit
}

// 树的遍历之查找所有的父节点
// list为树, id为目标节点的id, key为id匹配的字段
export const getAllNodes = (list: any, callBack: (arg: any) => void) => {
  for (const i in list) {
    callBack(list[i])
    if (list[i].children) getAllNodes(list[i].children, callBack)
  }
}
